#!/bin/ash -efu
#
# mki-expand-pkgs
#
# This file is part of mkimage
# Copyright (C) 2007-2009  Alexey Gladkov <gladkov.alexey@gmail.com>
#
# This file is covered by the GNU General Public License,
# which should be included with mkimage as the file COPYING.
#

. "${0%/*}"/mki-sh-functions

method="$1"; shift
[ "$#" -gt 0 ] ||
	exit 0

verbose "has started executing. method=$method"

case "$method" in
	simple)
		printf '%s\n' "$@"
		exit
		;;
	regexp)
		;;
	*)
		fatal "$method: Unknown method"
		;;
esac

aptboxdir="${PKGBOX:?global aptbox required}"
aptbox="$aptboxdir/aptbox"
[ -d "$aptbox" ] ||
	fatal "$aptbox: Not a directory"

tempdir="$dir/$PROG.verbose"
exit_handler() {
	local rc=$?
	trap - EXIT
	[ ! -d "$tempdir" ] || rm -rf -- "$tempdir"
	exit $rc
}

if [ -n "$verbose" ]; then
	[ ! -d "$tempdir" ] || rm -rf -- "$tempdir"
else
	trap exit_handler HUP INT QUIT TERM EXIT
fi
mkdir $verbose -- "$tempdir" >&2

mki_list_pkgs "$@" > "$tempdir/in-list"

cd "$tempdir"
> 'add-regexp' > 'rem-regexp' > 'pkg-list'

is_regexp() {
	case "$1" in
		*[\[\]\(\)\|\{\}\^\$\*\?]*) return 0 ;;
	esac
	return 1
}

while read -r p; do
	case "$p" in
		\!*)
			p="${p#\!}"
			fn='rem-regexp'
			is_regexp "$p" ||
				p="^$p\$"
			;;
		*[\<\>=]*)
			fn='pkg-list'
			;;
		*)
			fn='add-regexp'
			is_regexp "$p" ||
				fn='pkg-list'
			;;
	esac
	verbose "EXPAND: pattern='$p' stream='$fn'"
	printf '%s\n' "$p" >> "$fn"

done < 'in-list'

export LC_ALL=C LANG=C LANGUAGE=C

egrep -f 'add-regexp' "$aptbox/var/cache/pkgnames" |
	egrep -vf 'rem-regexp' |
	cat 'pkg-list' -
